﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        IBaseReponsitory<Roles> Roles;

        public AddRoleCommandHandler(IBaseReponsitory<Roles> Roles)
        {
            this.Roles = Roles;
        }

        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            if (request.Roles.Role_Name =="")
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "用户名称不为空",
                    Data = -1
                };
            }
            else 
            {
       var list = Roles.GetQuery().Where(x => x.Role_Name == request.Roles.Role_Name && !x.Role_IsDeleted).ToList();
            if (list.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "用户名称已存在",
                    Data = -1
                };
            }
            else
            {
                request.Roles.CreateTime = DateTime.Now;
                await Roles.AddAsync(request.Roles);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "添加应用成功",
                    Data = 1

                };
            }
            }
         
        }
    }
}
